package org.jeecg.modules.demo.crm.wxmsg;

import com.alibaba.fastjson.JSONObject;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.jeecg.common.api.vo.Result;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class TemplateMsgServer {

    @Autowired
    private WxMpService wxMpService;


    /**
     * 发送 消息模板
     * @param openId
     * @param templateId
     * @param url
     * @param body
     * @return
     * @throws WxErrorException
     */
    public Result send(String openId,String templateId,String url, JSONObject body) throws WxErrorException {
        Result result = new Result();
        try {
            List<WxMpTemplateData> data = body.entrySet()
                    .stream()
                    .map(e -> new WxMpTemplateData(
                            e.getKey(),
                            e.getValue().toString()))
                    .collect(Collectors.toList());

            WxMpTemplateMessage message = WxMpTemplateMessage.builder()
                    .toUser(openId)
                    .templateId(templateId)
                    .url(url)
                    .data(data)
                    .build();
            String rest = wxMpService.getTemplateMsgService().sendTemplateMsg(message);
            result.setSuccess(true);
            result.setMessage(rest);
            result.setCode(200);
           return result;
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage(e.getMessage());
            result.setCode(500);
            return result;
        }

    }
}
